package com.lanhai.crowd.mvc.handler;

import com.lanhai.crowd.entity.Menu;
import com.lanhai.crowd.service.api.MenuService;
import com.lanhai.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@RestController
public class MenuController {

    @Autowired
    private MenuService menuService;


    @RequestMapping("/menu/get/whole/tree.json")
    public ResultEntity<Menu> getWholeTree() {

        // 1.查询全部的Menu
        List<Menu> menuList = menuService.getAll();

        // 2.存储根节点
        Menu root = null;

        // 准备map存储父节点
        HashMap<Integer, Menu> hashMap = new HashMap<>();

        // 3.遍历list，找出父节点
        for (Menu menu : menuList) {
            // 4.获取当前menu的Pid和id
            Integer id = menu.getId();
            Integer pid = menu.getPid();
            Integer isFather = menu.getIsFather();

            // 5.检查Pid是否为null
            if(null == pid && Objects.equals(1, isFather)) {
                hashMap.put(id, menu);
                root = menu;
                continue;
            }

            // 如果是父节点，存入map
            if(Objects.equals(1, isFather)) {
                hashMap.put(id, menu);
            }
        }

        // 循环menuList,将子节点装配到父节点中
        for (Menu menu : menuList) {
            Integer pid = menu.getPid();

            // 查看该节点是谁的子节点
            if(hashMap.containsKey(pid)) {
                // 获取menu
                Menu parent = hashMap.get(pid);

                // 将该子节点放入父节点
                parent.getChildren().add(menu);
            }
        }


        // 7.将父节点返回给浏览器
        return ResultEntity.data(root);
    }

    @RequestMapping("/menu/save.json")
    public ResultEntity<String> saveMenu(Menu menu) {

        menuService.saveMenu(menu);

        return ResultEntity.ok();
    }

    @RequestMapping("/menu/edit.json")
    public ResultEntity<String> editMenu(Menu menu) {

        menuService.updateMenu(menu);

        return ResultEntity.ok();
    }

    @RequestMapping("/menu/remove.json")
    public ResultEntity<String> removeMenu(@RequestParam("id") Integer id) {

        menuService.deleteMenu(id);

        return ResultEntity.ok();
    }



}
